package com.blog.controller;

import com.blog.entity.Blog;
import com.blog.lucene.BlogIndex;
import com.blog.service.BlogService;
import com.blog.service.CommentService;
import com.blog.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({"/blog"})
public class BlogController {
    @Resource
    private BlogService blogService;
    @Resource
    private CommentService commentService;
    private BlogIndex blogIndex = new BlogIndex();

    @RequestMapping("/articles/{id}")
    public ModelAndView details(@PathVariable("id") Integer id, HttpServletRequest request) throws Exception {

        ModelAndView mav = new ModelAndView();

        //根据主键查询博客信息
        Blog blog = blogService.findById(id);
        mav.addObject("blog", blog);
        blog.setClickHit(blog.getClickHit() + 1);//访问量+1
        blogService.update(blog);//更新博客信息

        //查询评论
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("blogId", blog.getId());
        map.put("state", 1);
        mav.addObject("commentList", commentService.list(map));

        //处理关键字
        String keyWords = blog.getKeyWord();

        if (StringUtil.isNotEmpty(keyWords)) {
            String[] arr = keyWords.split(" ");
            mav.addObject("keyWords", StringUtil.filterWhite(Arrays.asList(arr)));
        } else {
            mav.addObject("keyWords", null);
        }

        //上一篇和下一篇
        mav.addObject("pageCode", genUpAndDownPageCode(blogService.getLastBlog(id), blogService.getNextBlog(id), request.getServletContext().getContextPath()));
        mav.addObject("mainPage", "foreground/blog/view.jsp");//将显示内容替换为新的jsp页面
        mav.addObject("pageTitle", blog.getTitle() + "_我的博客");//页面标题也要改变

        mav.setViewName("index");//视图还是显示基本页面

        return mav;

    }

    //根据关键字查询
  @RequestMapping("/q")
  public ModelAndView search(@RequestParam(value="q", required=false) String q, @RequestParam(value="page", required=false) String page, HttpServletRequest request) throws Exception {

    if (StringUtil.isEmpty(page)) {
      page = "1";
    }
    ModelAndView mav = new ModelAndView();
    mav.addObject("mainPage", "foreground/blog/result.jsp");

    //在lucene中查询博客列表
    List<Blog> blogList = blogIndex.searchBlog(q.trim());
    int toIndex = blogList.size() >= Integer.parseInt(page) * 10 ? Integer.parseInt(page) * 10 : blogList.size();

    mav.addObject("blogList", blogList.subList((Integer.parseInt(page) - 1) * 10, toIndex));
    mav.addObject("pageCode", genUpAndDownPageCode(Integer.parseInt(page), blogList.size(), q,10, request.getServletContext().getContextPath()));
    mav.addObject("q", q);
    mav.addObject("resultTotal", blogList.size());
    mav.addObject("pageTitle", "'搜索关键字'" + q + "'结果页面_我的博客'");
    mav.setViewName("index");

    return mav;
  }

  //博客列表翻页，上一篇、下一篇
  private String genUpAndDownPageCode(Blog lastBlog, Blog nextBlog, String projectContext) {
    StringBuffer pageCode = new StringBuffer();

    if ((lastBlog == null) || (lastBlog.getId() == null)) {
      pageCode.append("<p>上一篇：没有了噢</p>");
    } else {
      pageCode.append("<p>上一篇：<a href='" + projectContext + "/blog/articles/" + lastBlog.getId() + ".html'>" + lastBlog.getTitle() + "</a></p>");
    }

    if ((nextBlog == null) || (nextBlog.getId() == null)) {
      pageCode.append("<p>下一篇：没有了噢</p>");
    } else {
      pageCode.append("<p>下一篇：<a href='" + projectContext + "/blog/articles/" + nextBlog.getId() + ".html'>" + nextBlog.getTitle() + "</a></p>");
    }

    return pageCode.toString();
  }

  //查询结果实现翻页
  private String genUpAndDownPageCode(Integer page, Integer totalNum, String q, Integer pageSize, String projectContext) {

    long totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;

    StringBuffer pageCode = new StringBuffer();

    if (totalPage == 0L) {
      return "";
    }

    pageCode.append("<nav>");
    pageCode.append("<ul class='pager' >");

    if (page> 1) {//如果当前页大于1
      pageCode.append("<li><a href='" + projectContext + "/blog/q.html?page=" + (page - 1) + "&q=" + q + "'>上一页</a></li>");
    } else {//如果当前页是第一页
      pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
    }

    if (page < totalPage) {//不是最后一页
      pageCode.append("<li><a href='" + projectContext + "/blog/q.html?page=" + (page + 1) + "&q=" + q + "'>下一页</a></li>");
    } else {
      pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
    }

    pageCode.append("</ul>");
    pageCode.append("</nav>");
    
    return pageCode.toString();
  }
}
